package pt.chukaku.gtgb.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import pt.chukaku.gtgb.Book;
import android.util.Log;

public class BookDepositoryCom {

	String isbn = "";
	Book book = null;

	public BookDepositoryCom(String isbn) {
		super();
		this.isbn = isbn;
		getInfo();
	}

	public Book getBook() {

		return book;
	}

	private void getInfo() {
		String url = "http://www.bookdepository.com/book/" + isbn;
		String str = lerPagina(url + "?selectCurrency=GBP");

		int posI, posF;
		// Author
		posI = str.indexOf("See all books by");
		posF = str.indexOf("</a>", posI);
		String author = str.substring(posI + 19, posF);

		// Title
		posI = str.indexOf("dc:title");
		posF = str.indexOf("</span>", posI);
		String title = str.substring(posI + 10, posF);

		// Price
		posI = str.indexOf("Our price");
		posF = str.indexOf("</strong>", posI);
		String price = str.substring(posI + 26, posF);

		// Cover
		posI = str.indexOf("<div class=\"image large\"");
		posI = str.indexOf("img src=",posI);
		posI = str.indexOf("src=", posI);
		posF = str.indexOf("\" alt=", posI);
		String cover = str.substring(posI + 5, posF);

		book = new Book(title, author, price, cover,url, "BookDepository.com");
	}

	private String lerPagina(String urltext) {
		URL url = null;
		try {
			url = new URL(urltext);
		} catch (MalformedURLException e) {
			log("url = new URL(urltext);");
			e.printStackTrace();
		}
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(url.openStream()));
		} catch (IOException e) {
			log("in = new BufferedReader(...);");
			e.printStackTrace();
		}
		String inputLine;
		String result = "";
		try {
			while ((inputLine = in.readLine()) != null) {
				// Process each line.
				result += inputLine;
			}
		} catch (IOException e) {
			log("inputLine = in.readLine()");
			e.printStackTrace();
		}
		try {
			in.close();
		} catch (IOException e) {
			log("in.close()");
			e.printStackTrace();
		}
		return result;
	}

	private void log(String position) {
		Log.d("GTG", "AphroheadCom: " + position);
	}
}
